package com.dhu.stylefit.service;

import com.dhu.stylefit.converter.ClothesConverter;
import com.dhu.stylefit.dao.*;
import com.dhu.stylefit.dto.ClothesDTO;
import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;


@Service
public class ClothesServiceImpl implements ClothesService{

    @Autowired
    private ClothesRepository clothesRepository;

    @Autowired
    private UsersRepository usersRepository;

    @Autowired
    private ClothesCategoryRepository clothesCategoryRepository;

    @Override
    public ClothesDTO getClothesById(long id) {
        try {
            Optional<Clothes> clothesOptional = clothesRepository.findById(id);
            Clothes clothes = clothesOptional.orElseThrow(() ->
                    new RuntimeException("Could not find clothes with ID: " + id)
            );
            return ClothesConverter.convertClothes(clothes);
        } catch (Exception e) {
            throw new RuntimeException("An error occurred while retrieving clothes with ID: " + id, e);
        }
    }

    @Override
    public Long addNewClothes(ClothesDTO clothesDTO) {
        if (clothesDTO == null) {
            throw new IllegalArgumentException("ClothesDTO cannot be null");
        }
        Clothes clothes = ClothesConverter.convertClothes(clothesDTO);
        try {
            Clothes savedClothes = clothesRepository.save(clothes);
            return savedClothes.getClothesId();
        } catch (Exception e) {
            throw new RuntimeException("Failed to save clothes: " + e.getMessage(), e);
        }
    }

    @Override
    public List<ClothesDTO> getClothesByUserId(long userId) {
        List<Clothes> clothesList = clothesRepository.findByUserId(userId);
        if (clothesList.isEmpty()) {
            throw new RuntimeException("No clothes found for user ID: " + userId);
        }
        return clothesList.stream()
                .map(ClothesConverter::convertClothes)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional
    public ClothesDTO updateClothes(ClothesDTO clothesDTO) {
        // 检查输入的 ClothesDTO 是否有效
        if (clothesDTO == null || clothesDTO.getClothesId() == null) {
            throw new IllegalArgumentException("Invalid ClothesDTO or clothesId is null");
        }

        // 查询数据库中是否存在该服装记录
        Optional<Clothes> clothesOptional = clothesRepository.findById(clothesDTO.getClothesId());
        if (!clothesOptional.isPresent()) {
            throw new RuntimeException("Clothes with id " + clothesDTO.getClothesId() + " not found");
        }

        // 获取查找到的服装实体
        Clothes clothes = clothesOptional.get();

        // 检查用户 ID 是否合法
        if (clothesDTO.getUserId() != null) {
            Optional<Users> userOptional = usersRepository.findById(clothesDTO.getUserId());
            if (!userOptional.isPresent()) {
                throw new RuntimeException("User with id " + clothesDTO.getUserId() + " not found");
            }
            clothes.setUserId(clothesDTO.getUserId());
        }

        // 检查类别 ID 是否合法
        if (clothesDTO.getCategoryId() != null) {
            Long categoryId = clothesDTO.getCategoryId();
            if (categoryId < 1 || categoryId > 4) {
                throw new RuntimeException("Invalid category ID. Category ID must be between 1 and 4.");
            }
            clothes.setCategory(categoryId);
        }

        // 更新其他服装信息
        if (clothesDTO.getName() != null) {
            clothes.setName(clothesDTO.getName());
        }
        if (clothesDTO.getDescription() != null) {
            clothes.setDescription(clothesDTO.getDescription());
        }
        if (clothesDTO.getImageUrl() != null) {
            clothes.setImageUrl(clothesDTO.getImageUrl());
        }
        if (clothesDTO.getCreatedAt() != null) {
            clothes.setCreatedAt(clothesDTO.getCreatedAt());
        }

        // 保存更新后的记录
        Clothes updatedClothes = clothesRepository.save(clothes);

        // 返回更新后的服装信息
        return ClothesConverter.convertClothes(updatedClothes);
    }

    @Override
    public void deleteClothesById(long id) {
        if (id <= 0) {
            throw new IllegalArgumentException("Invalid clothes ID. ID must be greater than 0.");
        }
        Optional<Clothes> clothesOptional = clothesRepository.findById(id);

        if (clothesOptional.isPresent()) {
            try {
                clothesRepository.deleteById(id);
            } catch (Exception e) {
                throw new RuntimeException("Failed to delete clothes with ID " + id + ". Please try again later.", e);
            }
        } else {
            throw new RuntimeException("Clothes with ID " + id + " not found. Cannot perform delete operation.");
        }
    }

    // 获取指定用户某个分类下全部服装
    @Override
    public List<ClothesDTO> getClothesByUserIdAndCategoryId(long userId, long categoryId) {
        List<Clothes> clothesList = clothesRepository.findByUserIdAndClothesCategory(userId, categoryId);

        if (clothesList.isEmpty()) {
            throw new RuntimeException("No clothes found for user ID: " + userId + " and category ID: " + categoryId);
        }

        return clothesList.stream()
                .map(ClothesConverter::convertClothes)
                .collect(Collectors.toList());
    }

    @Override
    public Clothes saveClothes(Clothes clothes) {
        return clothesRepository.save(clothes);
    }
}
